﻿
namespace WebCommit.Common.Helpers
{
	using System;
	using System.Security.Cryptography;
	using System.Text;
	using System.IO;
	using System.Net;
	using log4net;
	using System.Web.Mvc;
	using WebCommit.Common.Entitys;

	public class Utility
	{
		public static string Hash(string url)
		{
			MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
			byte[] bs = Encoding.UTF8.GetBytes(url);
			bs = x.ComputeHash(bs);
			System.Text.StringBuilder s = new System.Text.StringBuilder();
			foreach (byte b in bs)
			{
				s.Append(b.ToString("x2").ToLower());
			}

			return s.ToString();
		}

		/// <summary>
		/// foamliu, 2009/12/27.
		/// 爬虫需要两个URL是否指向相同的页面这一点可以被迅速检测出来, 这就需要URL规范化.
		/// URL规范化做的主要的事情:
		/// 转换为小写
		/// 相对URL转换成绝对URL
		/// 删除默认端口号
		/// 根目录添加斜杠
		/// 猜测的目录添加尾部斜杠
		/// 删除分块
		/// 解析路径
		/// 删除缺省名字
		/// 解码禁用字符
		/// 
		/// 更多信息参照RFC3986:
		/// http://tools.ietf.org/html/rfc3986
		/// </summary>
		/// <param name="strURL"></param>
		public static void Normalize(string baseUri, ref string strUri)
		{
			// 相对URL转换成绝对URL
			if (strUri.StartsWith("/"))
			{
				strUri = baseUri + strUri.Substring(1);
			}

			// 当查询字符串为空时去掉问号"?"
			if (strUri.EndsWith("?"))
				strUri = strUri.Substring(0, strUri.Length - 1);

			// 转换为小写
			strUri = strUri.ToLower();

			// 删除默认端口号
			// 解析路径
			// 解码转义字符
			Uri tempUri = new Uri(strUri);
			strUri = tempUri.ToString();

			// 根目录添加斜杠
			int posTailingSlash = strUri.IndexOf("/", 8);
			if (posTailingSlash == -1)
				strUri += '/';

			// 猜测的目录添加尾部斜杠
			if (posTailingSlash != -1 && !strUri.EndsWith("/") && strUri.IndexOf(".", posTailingSlash) == -1)
				strUri += '/';

			// 删除分块
			int posFragment = strUri.IndexOf("#");
			if (posFragment != -1)
			{
				strUri = strUri.Substring(0, posFragment);
			}

			// 删除缺省名字
			string[] DefaultDirectoryIndexes = 
            {
                "index.html",
                "default.asp",
                "default.aspx",
            };
			foreach (string index in DefaultDirectoryIndexes)
			{
				if (strUri.EndsWith(index))
				{
					strUri = strUri.Substring(0, (strUri.Length - index.Length));
					break;
				}
			}
		}

		public static void Normalize(ref string strUri)
		{
			Normalize(string.Empty, ref strUri);
		}

		public static string GetBaseUri(string strUri)
		{
			string baseUri;
			Uri uri = new Uri(strUri);
			string port = string.Empty;
			if (!uri.IsDefaultPort)
				port = ":" + uri.Port;
			baseUri = uri.Scheme + "://" + uri.Host + port + "/";

			return baseUri;

		}

		public static string GetExtensionByMimeType(string mimeType)
		{
			int pos;
			if ((pos = mimeType.IndexOf('/')) != -1)
			{
				return mimeType.Substring(pos + 1);
			}
			return string.Empty;
		}

		public static HttpWebRequest CreateWebRequest(string url)
		{
			HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
			req.AllowAutoRedirect = true;
			req.CookieContainer = new CookieContainer();
			req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
			//req.Connection = "close";
			req.Date = DateTime.Now;
			req.KeepAlive = false;
			req.Accept = "text/html";

			//req.Headers.Add(HttpRequestHeader.Accept, "text/html");
			req.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN");
			req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
			//req.Headers.Add(HttpRequestHeader.Connection, "close");
			req.Headers.Add(HttpRequestHeader.Pragma, "no-cache");

			req.Timeout = 30000;
			return req;
		}


		public static bool IsNumeric(string str)
		{
			try { int i = Convert.ToInt32(str); return true; }
			catch { return false; }
		}

		/// <summary>
		/// 获取服务器根域名  
		/// </summary>
		/// <returns></returns>
		public static string GetRootDomain(string link)
		{
			string str = (new Uri(link)).Host;//此处获取值转换为小写
			if (str.IndexOf('.') > 0)
			{
				string[] strArr = str.Split('.');
				string lastStr = strArr.GetValue(strArr.Length - 1).ToString();
				if (IsNumeric(lastStr)) //如果最后一位是数字，那么说明是IP地址
				{
					return str;
					//return str.Replace(".", ""); //替换.为纯数字输出 
				}
				else //否则为域名
				{
					string[] domainRules = ".com.cn|.net.cn|.org.cn|.gov.cn|.com|.net|.cn|.org|.cc|.me|.tel|.mobi|.asia|.biz|.info|.name|.tv|.hk|.公司|.中国|.网络".Split('|');
					string findStr = string.Empty;
					string replaceStr = string.Empty;
					string returnStr = string.Empty;
					for (int i = 0; i < domainRules.Length; i++)
					{
						if (str.EndsWith(domainRules[i].ToLower())) //如果最后有找到匹配项
						{
							findStr = domainRules[i].ToString(); //www.px915.COM
							replaceStr = str.Replace(findStr, ""); //将匹配项替换为空，便于再次判断
							if (replaceStr.IndexOf('.') > 0) //存在二级域名或者三级，比如：www.px915
							{
								string[] replaceArr = replaceStr.Split('.'); // www px915
								returnStr = replaceArr.GetValue(replaceArr.Length - 1).ToString() + findStr;
								return returnStr;
							}
							else //px915
							{
								returnStr = replaceStr + findStr; //连接起来输出为：px915.com
								return returnStr;
							};
						}
						else
						{ returnStr = str; }
					}
					return returnStr;
				}
			}
			else
			{
				return str;
			}
		}


		/// <summary>
		/// 考虑：会不会占用太多内存？
		/// </summary>
		/// <param name="stream"></param>
		/// <returns></returns>
		public static byte[] ReadInstreamIntoMemory(Stream stream)
		{
			int bufferSize = 16384;
			byte[] buffer = new byte[bufferSize];
			MemoryStream ms = new MemoryStream();
			while (true)
			{
				int numBytesRead = stream.Read(buffer, 0, bufferSize);
				if (numBytesRead <= 0) break;
				ms.Write(buffer, 0, numBytesRead);
			}
			return ms.ToArray();
		}

		private static bool loggerIsCfg = false;
		public static void Log(object msg, Exception ex)
		{
			if (!loggerIsCfg)
			{
				log4net.Config.XmlConfigurator.Configure();
				loggerIsCfg = true;
			}
			ILog log = LogManager.GetLogger("FileAppender");
			log.Error(msg, ex);

		}

		public static T GetAppCfg<T>(string key)
		{
			string v = System.Configuration.ConfigurationManager.AppSettings[key];
			return (T)Convert.ChangeType(v, typeof(T));
		}

		public static string GetAppCfg(string key)
		{
			return GetAppCfg<string>(key);
		}

		/// <summary>
		/// 获取当前应用程序路径
		/// </summary>
		/// <returns></returns>
		public static string GetCurrentAppPath()
		{
			string path,curDir,basDir = "";
			curDir = NormalizePath(System.Environment.CurrentDirectory);
			basDir = NormalizePath(AppDomain.CurrentDomain.BaseDirectory);
			if (curDir == basDir)//Windows应用程序则相等
			{
				path = basDir;
			}
			else
			{
				path = basDir + "Bin\\";
			}
			return path;
		}

		public static string NormalizePath(string path)
		{
			if (path.LastIndexOf("\\") != path.Length - 1 && path.LastIndexOf("/") != path.Length - 1)
			{
				path = path + "\\";
			}
			return path;
		}
		/// <summary>
		/// 获取当前网站地址
		/// </summary>
		/// <returns></returns>
		public static string GetCurrentSiteUrl()
		{
			Uri uri = System.Web.HttpContext.Current.Request.Url;
			string url = "http://" + uri.Host + (uri.Port == 80 ? "" : ":" + uri.Port.ToString()) + "/";
			return url;
		}



	}
}
